package com.wk.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.wk.job.Task;

public class TaskDatabase {
	public static final String STANDING_BY = "待生产";
	public static final String PRODUCING = "生产中";

	public String table = "t_business_production_plan_management";
	public String column_id = "id";
	public String column_plan = "production_plan_name";
	public String column_product = "product_type";
	public String column_region = "region_range";
	public String column_state = "production_status";
	public String column_beginTime = "production_begin_time";

	public void prepare(Connection connection) throws SQLException {
		queryTasks = connection.prepareStatement(
				"SELECT " + column_id + ", " + column_plan + ", " + column_product + ", " + column_region + " FROM "
						+ table + " WHERE " + column_state + " = ? AND " + column_beginTime + " <= ?");
		setState = connection
				.prepareStatement("UPDATE " + table + " SET " + column_state + " = ? WHERE " + column_id + " = ?");
	}

	/**
	 * 外观方法：加载待生产的Task到程序中，并设置它们的状态为“生产中”<br>
	 * 注：不提供事务支持
	 * 
	 * @param tasks
	 *            收集参数：收集待生产的Task
	 * @throws SQLException
	 *             查询或设置状态失败
	 */
	public void startAll(Collection<Task> tasks) throws SQLException {
		List<Task> _tasks = new LinkedList<>();
		queryAll(STANDING_BY, now(), _tasks);
		
		for(Task task : _tasks){
			setState(task.getTaskId(), PRODUCING);
		}
		
		tasks.addAll(_tasks);
	}

	/**
	 * 查询符合条件的Task
	 * 
	 * @param state
	 *            Task状态。仅查询此状态的Task<br>
	 *            可选项：<br>
	 *            待生产{@link TaskDatabase#STANDING_BY}<br>
	 *            生产中{@link TaskDatabase#PRODUCING}）
	 * @param beginTime
	 *            Task起始时间。仅查询在该时间点及之前开始的Task<br>
	 *            例：2017-04-13；2017-4-13
	 * @param results
	 *            收集参数：收集查询到的task
	 * 
	 * @throws SQLException
	 *             查询失败
	 */
	public void queryAll(String state, String beginTime, Collection<Task> results) throws SQLException {
		queryTasks.setString(1, state);
		queryTasks.setString(2, beginTime);
		ResultSet resultSet = queryTasks.executeQuery();
		while (resultSet.next()) {
			results.add(parseTask(resultSet));
		}
		resultSet.close();
	}

	/**
	 * 设置指定的Task的状态<br>
	 * 注：未做批量更新优化，可能存在性能瓶颈<br>
	 * 参考资料：Statement和PreparedStatement的批量提交<br>
	 * http://blog.csdn.net/iloveyin/article/details/6954691
	 * 
	 * @param id
	 *            指定Task的id
	 * @param state
	 *            要设置的状态
	 * @throws SQLException
	 *             提交请求失败
	 * @return 修改的Task数
	 */
	public int setState(int id, String state) throws SQLException {
		setState.setString(1, state);
		setState.setInt(2, id);
		return setState.executeUpdate();
	}

	/* 获得当前日期，形如“2017-04-15” */
	public static String now() {
		SimpleDateFormat timeFormate = new SimpleDateFormat("yyyy-MM-dd");
		return timeFormate.format(new Date());
	}

	/* 把{@link ResultSet}的当前元素转为{@link Task}对象 */
	private Task parseTask(ResultSet resultSet) throws SQLException {
		int id = resultSet.getInt(1);
		String plan = resultSet.getString(2);
		String product = resultSet.getString(3);
		String region = resultSet.getString(4);

		return new Task(id, plan, product, region);
	}

	private PreparedStatement queryTasks;
	private PreparedStatement setState;
}
